package com.sobjal.android;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;

import com.sobjal.android.devices.*;
import com.sobjal.android.utils.SmartObjects;
import com.sobjal.android.xml.SendXml;
import com.sobjal.android.xml.XmlParser;
import com.sobjal.android.xml.XmlWriter;

/**
 * 
 * @author Fabio Monteiro, Lu Chen
 *
 * Class to performs action through XML for several devices at a time
 * 
 */
public class ActionSeveral extends Activity{
	
	public static final String PREFS_NAME = "MyPreferences";
	private List<Device>  ld;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTitle("Choose an action");

		//getting the previously selected several Smartobjects ids
		Bundle b = getIntent().getExtras();
		ArrayList<String> ids = b.getStringArrayList("severalSelectedObjectsId");

		//final List<Device> ld = (ArrayList<Device>) b.getSerializable("severalSelectedObjects");

		 ld = new ArrayList<Device>();

		//putting them into a List<Device>
		for (int i = 0; i < ids.size(); i++){
			Device d = SmartObjects.getADeviceById(ids.get(i));
			//Toast.makeText(getApplicationContext(),d.getName(),Toast.LENGTH_SHORT).show();		
			ld.add(d);	
		}

		if(SmartObjects.checkIfTypeInTheList("mydeskfriend", ld)){
			
			/**
			 * **************************************************
			 * Several different types of devices
			 * **************************************************
			 */
			setContentView(R.layout.action_several_devices);

			Button buttonSendMess = (Button) findViewById(R.id.Button01_several);
			buttonSendMess.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					EditText text = (EditText) findViewById(R.id.EditText01_several);
					String message = text.getText().toString();

					Iterator<Device> i = ld.iterator();

					while(i.hasNext()){	
						Device d = i.next();

						String xml = XmlWriter.writeXmlForSendingMessage(d.getIdDevice(), message);
						//calling webservice
						String response = SendXml.sendXmlToServer(xml); //the response

						ArrayList<String> temp = XmlParser.parseGeneralGetMsgAndComment(response);
						String comment = temp.get(1);
						 

						String name = d.getName();

						Toast.makeText(getApplicationContext(),name + ": "+ comment, Toast.LENGTH_SHORT).show();
						//Toast.makeText(getApplicationContext(), name + ": " + comment , Toast.LENGTH_SHORT).show();		
					}	
				}
			});

		}else{
			/**
			 * *****************************************************
			 * Several Nabaztags only
			 * ******************************************************
			 */
			setContentView(R.layout.action_several_nabaztag);

			//send message several nabaztags
			Button buttonSendMessNabaz = (Button) findViewById(R.id.ButtonMessage_severalNabaz);
			buttonSendMessNabaz.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub

					EditText text = (EditText) findViewById(R.id.EditText01_severalNabaz);

					String message = text.getText().toString();

					Iterator<Device> i = ld.iterator();

					while(i.hasNext()){	
						Device d = i.next();
						
						String xml = XmlWriter.writeXmlForSendingMessage(d.getIdDevice(), message);
						//calling webservice
						String xmlresponse = SendXml.sendXmlToServer(xml); //the response
						
						ArrayList<String> temp = XmlParser.parseGeneralGetMsgAndComment(xmlresponse);
						String comment = temp.get(1);
						 
						String name = d.getName();
						
						Toast.makeText(getApplicationContext(), name + ": " + comment , Toast.LENGTH_SHORT).show();

					}
				}

			});

			//resetting ears several nabazs
			Button buttonResetEars = (Button) findViewById(R.id.ButtonOreille_severalNabaz);
			buttonResetEars.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					Iterator<Device> i = ld.iterator();

					while(i.hasNext()){	
						Device d = i.next();

						String xml = XmlWriter.writeXmlForResettingEars(d.getIdDevice());
						//calling webservice
						String response = SendXml.sendXmlToServer(xml); //the response
						
						ArrayList<String> temp = XmlParser.parseGeneralGetMsgAndComment(response);
						String comment = temp.get(1);
						
						String name = d.getName();
						Toast.makeText(getApplicationContext(), name + ": "+ comment , Toast.LENGTH_SHORT).show();	

					}		
				}
			});

			//Show Friends several Nabaz
			Button buttonGetFriendsSeveralNabaz = (Button) findViewById(R.id.ButtonGetFriends_severalNabaz);
			buttonGetFriendsSeveralNabaz.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					Iterator<Device> i = ld.iterator();
					//writing xml

					while(i.hasNext()){
						Device d = i.next();

						String xml = XmlWriter.writeXmlForGettingFriends(d.getIdDevice());

						//calling the webservice
						String xmlResponse = SendXml.sendXmlToServer(xml);
						String name = d.getName();

						ArrayList<String> friendsList = new ArrayList<String>();

						friendsList = XmlParser.parseGetFriendsResponse(xmlResponse);

						if (friendsList.size() == 0){
							Toast.makeText(getApplicationContext(), name+ " got no friends :(", Toast.LENGTH_SHORT).show();
						}else{
							Iterator iFriend = friendsList.iterator();
							while(iFriend.hasNext()){
								Toast.makeText(getApplicationContext(), name+ "'s friend : "+(String) iFriend.next(), Toast.LENGTH_SHORT).show();
							}
						}
					}

				}
			});
			
			//Wake up several nabazs
			Button buttonWakeUpSeveralNabaz = (Button) findViewById(R.id.ButtonWakeUp_severalNabaz);
			buttonWakeUpSeveralNabaz.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					Iterator<Device> i = ld.iterator();
					//writing xml

					while(i.hasNext()){
						Device d = i.next();

						String xml = XmlWriter.writeXmlForWakeUp(d.getIdDevice());

						//calling the webservice
						String xmlResponse = SendXml.sendXmlToServer(xml);

						ArrayList<String> temp = XmlParser.parseGeneralGetMsgAndComment(xmlResponse);
						
						String comment = temp.get(1);
						
						String name = d.getName();
						Toast.makeText(getApplicationContext(), name + ": "+ comment , Toast.LENGTH_SHORT).show();
					}

				}
			});
			
			//Is sleeping several nabazs
			Button buttonIsSleepingSeveralNabaz = (Button) findViewById(R.id.ButtonIsSleeping_severalNabaz);
			buttonIsSleepingSeveralNabaz.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					Iterator<Device> i = ld.iterator();
					//writing xml

					while(i.hasNext()){
						Device d = i.next();

						String xml = XmlWriter.writeXmlForIsSleeping(d.getIdDevice());

						//calling the webservice
						String xmlResponse = SendXml.sendXmlToServer(xml);

						ArrayList<String> response = XmlParser.parseIsSleepingResponse(xmlResponse);
						
						String status = response.get(0);
						
						String name = d.getName();
						Toast.makeText(getApplicationContext(), name + "'s sleeping status: "+ status , Toast.LENGTH_SHORT).show();
					}

				}
			});
			
			// handling sending a song  for several nabazs
			Button buttonSong = (Button) findViewById(R.id.ButtonSong_severalNabaz);
			buttonSong.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					// TODO Auto-generated method stub
					actionDialogPourBntSong();
				}
			});
			
			//Static chor/dance several nabazs
			Button buttonChorSeveralNabaz = (Button) findViewById(R.id.ButtonDanceNabaztag_several);
			buttonChorSeveralNabaz.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					Iterator<Device> i = ld.iterator();
					//writing xml

					while(i.hasNext()){
						Device d = i.next();

						String xml = XmlWriter.writeXmlForSendingAStaticChoregraphy(d.getIdDevice());

						//calling the webservice
						String xmlResponse = SendXml.sendXmlToServer(xml);

						ArrayList<String> temp = XmlParser.parseGeneralGetMsgAndComment(xmlResponse);
						
						String comment = temp.get(1);
						
						String name = d.getName();
						Toast.makeText(getApplicationContext(), name + ": "+ comment , Toast.LENGTH_SHORT).show();
					}

				}
			});
			
			//make sleep several nabazs
			Button buttonMakeSleepSeveralNabaz = (Button) findViewById(R.id.ButtonMakeSleep_severalNabaz);
			buttonMakeSleepSeveralNabaz.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					Iterator<Device> i = ld.iterator();
					
					while(i.hasNext()){
						Device d = i.next();

						String xml = XmlWriter.writeXmlForMakeSleep(d.getIdDevice());

						//calling the webservice
						String xmlResponse = SendXml.sendXmlToServer(xml);

						ArrayList<String> temp = XmlParser.parseGeneralGetMsgAndComment(xmlResponse);
						
						String comment = temp.get(1);
						
						String name = d.getName();
						Toast.makeText(getApplicationContext(), name + ": "+ comment , Toast.LENGTH_SHORT).show();
					}

				}
			});
			
			
		}
	}
	// Regular Expression, check URL address
	private boolean checkString(String s) {
		return s.matches("[a-zA-z]+://[^/s]*");
	}

	
	//action button song
	public void actionDialogPourBntSong() {
		final EditText e = new EditText(this);
		

		SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
		String lastValue = prefs.getString("streamLink", "");
		e.setText(lastValue);
		
		new AlertDialog.Builder(this)
				.setTitle("URL")
				.setIcon(R.drawable.musicicon)
				.setView(e)
				.setPositiveButton(" Ok ",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								if (checkString(e.getText().toString())) {
									String text = (e.getText().toString());
									
									//put last link in preferences
									SharedPreferences lastLink = getSharedPreferences(PREFS_NAME, 0);
									SharedPreferences.Editor editor = lastLink.edit();
									editor.putString("streamLink", text);
									editor.commit();
									
									//Send the URL to all devices
									Iterator<Device> i = ld.iterator();
									
									while(i.hasNext()){
										Device d = i.next();
										
										String name = d.getName();
										// writing xml
										String xml = XmlWriter
										.writeXmlForPlayURL( d.getIdDevice(), text);
										
										// calling the webservice
										String xmlResponse = SendXml
												.sendXmlToServer(xml);

										ArrayList<String> temp = XmlParser
												.parseGeneralGetMsgAndComment(xmlResponse);
										String comment = temp.get(1);

										Toast.makeText(getApplicationContext(),
												name + ": " + comment,
												Toast.LENGTH_SHORT).show();
									}//end while

								} else {
									new AlertDialog.Builder(e.getContext())
											.setMessage("URL is not correct")
											.setPositiveButton(
													"Yes",
													new DialogInterface.OnClickListener() {
														public void onClick(
																DialogInterface dialog,
																int id) {
															actionDialogPourBntSong();
														}
													}).show();

								}
							}
						}).show();
	}
	
	//for menu
@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		 
		LayoutInflater  factory = LayoutInflater.from(this);
		final View textEntryView = factory.inflate(R.layout.dialog_about, null);
		 
		switch (item.getItemId()) {
		case R.id.menulogin:
			// about function
			if (SmartObjects.SMART_OBJECTS_LIST.isEmpty()) {
				Intent intent = new Intent();
				intent.setClass(ActionSeveral.this, SobjalMain.class);
				startActivity(intent);
			} else {
				Intent intent = new Intent();
				intent.setClass(ActionSeveral.this, login.class);
				startActivity(intent);
			}
			return true;
		case R.id.menulogoff:
			// settings function
			new AlertDialog.Builder(this)
					.setMessage("Are you sure you want to exit?")
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									SmartObjects.SMART_OBJECTS_LIST = null;
									Intent intent = new Intent();
									intent.setClass(ActionSeveral.this,
											SobjalMain.class);
									startActivity(intent);
									ActionSeveral.this.finish();
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							}).show();
			return true;
		case R.id.menuabout:
			
			new AlertDialog.Builder(this)
			.setMessage("About")
			.setIcon(android.R.drawable.ic_menu_info_details)
			.setView(textEntryView).show();
		default:
			Log.e("Unknown menu item selected", " ");
			return false;
		}
	}
}	
